﻿using System;
using System.Collections.Generic;

namespace BaseAPI.BaseViewModel;

public class ResponseModel<T>
{
    /// <summary>
    /// 状态码（失败0，成功200）
    /// </summary>
    public int Code { get; set; }
    /// <summary>
    /// 消息
    /// </summary>
    public string Info { get; set; }
    /// <summary>
    /// 数据
    /// </summary>
    public T Data { get; set; }

    public PageResponse PageResponse { get; set; }

    /// <summary>
    /// 查询结果转换函数，一般用于在数据库查询完成后，二次本地查询组织返回数据
    /// </summary>
    /// <typeparam name="TU">返回的数据类型</typeparam>
    /// <param name="fun">将实体转换为返回数据类型的方法</param>
    /// <returns></returns>
    public ResponseModel<TU> Then<TU>(Func<T, TU> fun)
    {
        if (Code == 200)
        {
            try
            {
                return new ResponseModel<TU>()
                {
                    Code = Code,
                    Info = Info,
                    Data = fun(Data),
                    PageResponse = PageResponse,
                };
            }
            catch (Exception e)
            {
                return new ResponseModel<TU>
                {
                    Code = 0,
                    Info = e.Message
                };
            }
        }
        else
        {
            return new ResponseModel<TU>()
            {
                Code = Code,
                Info = Info,
            };
        }
    }

    public static ResponseModel<T> Success(T responseData, PageResponse pageResponse = null)
    {
        return new ResponseModel<T>()
        {
            Code = 200,
            Info = "成功",
            Data = responseData,
            PageResponse = pageResponse,
        };
    }

    public static ResponseModel<T> Failed(string msg = "失败")
    {
        return new ResponseModel<T>()
        {
            Code = 0,
            Info = msg,
        };
    }

    public static ResponseModel<T> ModelFailed(T responseData)
    {
        return new ResponseModel<T>()
        {
            Code = 0,
            Info = "模型验证失败",
            Data = responseData,
        };
    }

    public static ResponseModel<T> HandleError(Exception e)
    {
        var msg = HandleSpecialError(e);
        return new ResponseModel<T>()
        {
            Code = 0,
            Info = msg,
        };
    }

    private static string HandleSpecialError(Exception e)
    {
        string msg;
        switch (e.HResult)
        {
            case -2147024893:
                msg = "指定的目录不存在";
                break;
            default:
                msg = e.Message;
                break;
        }
        return msg;
    }
}

public class ModelError
{
    public string FieldName { get; set; }
    public List<string> ErrorDescriptions { get; set; }
}